<template>
  <div>
    <!-- 封装的的添加和编辑组件 -->
    <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" style="width:80%" placeholder="2-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
          <el-option v-for="item in employList" :key="item.id" :value="item.username" :label="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getEmployees } from '@/api/employee'
import { addDepartment, getDepartmentDetail, updateDepartmentDetail } from '@/api/department'
export default {
  name: 'VueAdminTemplateDeptdialog',
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 校验code  查看codeList中是否存在用户输入的code
    // 自定义校验规则，校验部门编码  value当前校验的值，collback是否通过校验
    const validCode = (rules, value, collback) => {
      // codeList只存放code的数组
      let codeList = this.originList.map(item => item.code)
      // 当用户点击了编辑的时候 需要将当前的对象排除在外，将剩下所有的code放进数组中，然后再进行校验
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // includes判断数组中是否存在某个值
      if (codeList.includes(value)) {
        collback(new Error(value + '已经存在'))
      } else {
        collback()
      }
    }
    // 校验部门名称name  同级部门名称不能相同
    const ValidName = (rules, value, callback) => {
      // 找到所有子部门
      // this.originList.filter(item=>item.pid===this.id)
      // 将所有子部门的部门名称放入新数组中进行校验，看用户输入的部门名称是否已经存在
      let nameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      // 点击编辑时，不能和自己的同级重名
      if (this.isEdit) {
        // 根据id找到当前的对象 找到自己的pid
        const pid = this.originList.find(item => item.id === this.id).pid
        // 根据pid找到自己的兄弟部门且排除自己,映射所有的name到nameList
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
      }
      if (nameList.includes(value)) {
        callback(new Error(value + '已经存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employList: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门名称要求2-50个字符', trigger: 'blur' },
          { validator: ValidName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: ['blur', 'change'] }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 300, message: '部门介绍要求1-300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  /*  watch: {
    id: {
      deep: true,
      handler() {
        this.getDepartment()
      },
      immediate: true // 立即侦听
    }
  }, */

  created() {
    this.getEmployeeList()
    this.getDepartment()
  },

  methods: {
    // 点击确定，发请求
    hSubmit() {
      // 兜底校验
      this.$refs.deptForm.validate(valid => {
        if (!valid) return
        // 通过isEdit是true还是false，来决定是新增操作还是编辑
        if (!this.isEdit) {
          this.doAdd()
        } else {
          this.doEdit()
        }
      })
    },
    async doAdd() {
      // 发请求，添加部门
      /* this.form = { ...this.form, pid: this.id }
      this.update(addDepartment, this.form) */
      try {
        this.form = { ...this.form, pid: this.id }
        const res = await addDepartment(this.form)
        // console.log(res)
        // 成功添加提示用户
        this.$message.success(res.message)
        // 刷新列表  子传父
        this.$emit('hSuccess')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    async doEdit() {
      // 修改部门信息
      // this.update(updateDepartmentDetail, this.form)
      try {
        const res = await updateDepartmentDetail(this.form)
        console.log(res)
        // 提示用户更新成功
        this.$message.success(res.message)
        // 关闭dialog,刷新页面
        this.$emit('hSuccess')
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    /* async update(query, data) {
      try {
        const res = await query(data)
        console.log(res)
        // 提示用户更新/添加成功
        this.$message.success(res.message)
        // 关闭dialog,刷新页面
        this.$emit('hSuccess')
      } catch (e) {
        this.$message.error(e.message)
      }
    }, */
    // 子组件不能修改dialogVisible的值，需要通过子传父实现
    hCancel() {
      this.$emit('close')
    },
    // 获取员工简单列表
    async getEmployeeList() {
      const res = await getEmployees()
      this.employList = res.data
      // console.log(res)
    },
    // 获取部门详情信息  当dialog出来的时候就要调用请求，判断isEdit是不是true，如果是，就要发请求回写数据
    async getDepartment() {
      if (!this.isEdit) return
      try {
        const res = await getDepartmentDetail(this.id)
        // console.log(res)
        this.form = res.data
      } catch (e) {
        console.log(e.message)
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
